<?php
/**
 * User zgh
 * Email 1803897171@qq.com
 * Date 2021/7/13
 **/

namespace app\admin\service;

use app\admin\item\LoginLoader;
use app\admin\pipeline\LoginAdapter;
use app\admin\validate\LoginValidate;
use app\common\model\AdminModel;
use app\common\model\AdminRoleModel;
use app\common\model\RolePrivilegeModel;
use app\common\model\SystemNodeModel;
use think\facade\Request;
use think\facade\Session;

class LoginService
{

    protected static function loginCallBack($type = 1, $admin = [])
    {
        if ($type == 1) {
            Session::set("admin_is_login", 1);
            Session::set("admin_username", $admin['username']);
            Session::set("admin_id", $admin['id']);
        } elseif ($type == 2) {
            Session::delete("admin_is_login");
            Session::delete("admin_username");
            Session::delete("admin_id");
        } else {
            return Session::has("admin_is_login") && Session::has("admin_username") && Session::has("admin_id");
        }
        return true;
    }

    public static function login($params)
    {
        $loader = new LoginLoader();
        $data = $loader->addVal($params)->addVerify(LoginValidate::class)->loadItem(); //验证数据的有效性
        $adapter = new LoginAdapter(AdminModel::class);
        $adapter = $adapter->where(["username" => $data['username'], "status" => 1]);
        $adapter->checkPassword($data['password'])->save(["last_login_ip" => Request::ip(), "last_login_time" => date("Y-m-d H:i:s")]);
        self::loginCallBack(1, $adapter->getData());
        return true;
    }

    /**
     * 退出登陆
     */
    public static function login_out()
    {
        self::loginCallBack(2);
    }


    /**
     * 判断是否已经登陆
     * @return bool
     */
    public static function isLogin()
    {
        return self::loginCallBack(3);
    }

    /**
     * 判断是否是超级管理员
     */
    public static function isSuperManger($admin_id)
    {
        if ($admin_id == 1) {
            return true;
        } else {
            return false;
        }
    }

    public static function getAdminId()
    {
        if (Session::has("admin_id")) {
            return Session::get("admin_id");
        } else {
            return 0;
        }
    }


    public static function getAdminNodeArr($admin_id)
    {
        if (LoginService::isSuperManger($admin_id)) {
            $node_arr = SystemNodeModel::column("node");
        } else {
            $node_arr = AdminRoleModel::alias("ar")
                ->join(RolePrivilegeModel::getMagicTableName() . " rp", "ar.role_id=rp.role_id")
                ->where(["ar.admin_id" => $admin_id, "ar.status" => 1])
                ->where(["rp.status" => 1])
                ->column("node");
        }
        return $node_arr;
    }


}